//
// Created by 28365 on 2025/3/11.
//

#include "../include/config/proceessing/UpdateTaskRunnable.h"
#include "../include/exception/UnConnectServerException.h"
#include "../include/exception/FileUnableDeleteException.h"
#include "obj/File.h"
#include "config/server_api/result_obj/ReqValue.h"
#include "obj/UpdateError.h"

void UpdateTaskRunnable::updateTask(ODUpdater &odUpdater,const Res *res, int nowVersion) {

    odUpdater.getLogger()->debug("启动线程更新资源-->" + res->getResPath());

    File *file;
    try {
        file = odUpdater.getFileProcessor()->getFile(odUpdater.getRootDirectory(),*res);

        if (!res->isDelete()){
            //更新类型
            do {

                ReqValue<string> reqValue = odUpdater.getUpdaterServer()->getResFile(*res,nowVersion,file->openOutStream(std::ios::binary),odUpdater);

                if (reqValue.getServerApiState() == SUCCESS){
                    //数据传输成功
                    break;
                } else if (reqValue.getServerApiState() == MAXIMUM_DOWNLOAD){
                    //并发上限
                    odUpdater.reducePoolSize();
                    odUpdater.awaitOneTaskDone();
                } else{
                    throw UnConnectServerException("获取资源下载失败");
                }

            } while (true);

        } else{
            //删除类型
            if (file->isExists()){
                odUpdater.getLogger()->info("正在删除文件->" + res->getResPath());
                if (!file->deleteFile()){
                    throw FileUnableDeleteException("文件无法删除->" + res->getResPath());
                }
            }
        }

        odUpdater.getLogger()->debug("资源更新完成->" + res->getResPath());
        odUpdater.getUpdateHandler()->postUpdate({res,nowVersion});
    }catch (std::exception &e){
        odUpdater.getLogger()->warn("资源更新出现异常->->" + res->getResPath(),e);
        odUpdater.getUpdateHandler()->updateError({res,nowVersion,e});
        odUpdater.addUpdateError(UpdateError(res,e));
    }

    delete file;

    //记录一次任务完成，无论成是否成功
    odUpdater.addEndTask();
}
